package com.example.main;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class Main01_Md5Test {

    public static void main(String[] args) {
        String s = encrypt3ToMD5("123456");
        String s1 = encryptToMD5("123456");
        System.out.println();
    }

    public static String encrypt3ToMD5(String str) {
        log.debug("MD5待加密字符串:\n{}" , str);
        String md5 = "  ";
        try {
            md5 = DigestUtils.md5DigestAsHex(str.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        log.debug("MD5加密结果:\n{}",md5);
        return md5;
    }

    public static String encryptToMD5(String str) {
        String s = org.apache.commons.codec.digest.DigestUtils.md5Hex(str);
        return s;
    }

    public static String encrypt3ToHmacSha256(String str) {
        String key="key";
        String algorithm="HmacSHA256";
        log.debug("HmacSha256待加密字符串:\n{}" , str);
        String cipher = "  ";
        try {
            Mac hmacSHA256 = Mac.getInstance(algorithm);
            SecretKey secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), algorithm);
            hmacSHA256.init(secretKey);
            byte[] bytes = hmacSHA256.doFinal(str.getBytes(StandardCharsets.UTF_8));

            cipher  = bytesToHexStr(bytes);
        } catch ( NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }
        log.debug("HmacSha256加密结果:\n{}",cipher );
        return cipher ;
    }

    public static String bytesToHexStr(byte[] bytes) {
        StringBuilder hexStr = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            hexStr.append(hex);
        }
        return hexStr.toString();
    }

}
